package com.pan.studentmaster;

import java.io.File;

import android.graphics.*;
import android.database.Cursor;
import android.os.Environment;
import android.util.Log;

public class BookMaster {

	static public final int		BOOK_WIDTH = 800;
	static public final int		BOOK_HEIGHT = 1200;
	static public final int		BOOK_LINE_HEIGHT = 60;
	static public final int		BOOK_SBLOCK_HEIGHT = 60;
	static public final int		BOOK_SBLOCK_WIDTH = 50;
	static public final int		BOOK_BBLOCK_HEIGHT = 120;
	static public final int		BOOK_BBLOCK_WIDTH = 120;
	static public Paint			GRID_PAINT = null;
	static public final int		BG_COLOR = Color.rgb(242, 220, 180);

	static {
		GRID_PAINT = new Paint();
		GRID_PAINT.setAntiAlias(true);
		GRID_PAINT.setDither(true);
		GRID_PAINT.setStyle(Paint.Style.STROKE);
		GRID_PAINT.setStrokeJoin(Paint.Join.ROUND);
		GRID_PAINT.setStrokeCap(Paint.Cap.ROUND);
		GRID_PAINT.setXfermode(null);
		GRID_PAINT.setAlpha(0xFF);
		GRID_PAINT.setColor(Color.CYAN);
	}

	static public BookMaster instance() {
		if(_instance == null)
			_instance = new BookMaster();
		return _instance;
	}

	public Bitmap getBitmap(int bookId, int page) {
		Log.i("BOOKMASTER", "Get bitmap for book " + bookId + " page " + page);
		Cursor cursor = DB.instance().getBookInfo(bookId);
		if(page == 0 && cursor.getInt(cursor.getColumnIndex(DB.BOOK._BOOKTYPE)) != DB.BOOK_TEXT)
			return getCover();
		switch(cursor.getInt(cursor.getColumnIndex(DB.BOOK._BOOKTYPE))) {
			case DB.BOOK_TEXT : {
				return getPDFBitmap(cursor.getString(cursor.getColumnIndex(DB.BOOK._TITLE)),
					cursor.getString(cursor.getColumnIndex(DB.BOOK._SUBTITLE)), page);
			}
			case DB.BOOK_LINE : {
				if(_bmpLine == null) {
					_bmpLine = Bitmap.createBitmap(BOOK_WIDTH, BOOK_HEIGHT, Bitmap.Config.ARGB_8888);
					Canvas canvas = new Canvas(_bmpLine);
					canvas.drawColor(BG_COLOR);
					int start = BOOK_LINE_HEIGHT * 2;
					while (start < BOOK_HEIGHT) {
						canvas.drawLine(0, start, BOOK_WIDTH, start, GRID_PAINT);
						start += BOOK_LINE_HEIGHT;
					}
				}
				return _bmpLine;
			}
			case DB.BOOK_SBLOCK : {
				if(_bmpSblock == null) {
					_bmpSblock = Bitmap.createBitmap(BOOK_WIDTH, BOOK_HEIGHT, Bitmap.Config.ARGB_8888);
					Canvas canvas = new Canvas(_bmpSblock);
					canvas.drawColor(BG_COLOR);
					int start = BOOK_SBLOCK_HEIGHT * 2;
					while (start < BOOK_HEIGHT) {
						canvas.drawLine(0, start, BOOK_WIDTH, start, GRID_PAINT);
						start += BOOK_SBLOCK_HEIGHT;
					}
					start = BOOK_SBLOCK_WIDTH;
					while (start < BOOK_WIDTH) {
						canvas.drawLine(start, 0, start, BOOK_HEIGHT, GRID_PAINT);
						start += BOOK_SBLOCK_HEIGHT;
					}
				}
				return _bmpSblock;
			}
			case DB.BOOK_BBLOCK : {
				if(_bmpBblock == null) {
					_bmpBblock = Bitmap.createBitmap(BOOK_WIDTH, BOOK_HEIGHT, Bitmap.Config.ARGB_8888);
					Canvas canvas = new Canvas(_bmpBblock);
					canvas.drawColor(BG_COLOR);
					int start = BOOK_BBLOCK_HEIGHT * 2;
					while (start < BOOK_HEIGHT) {
						canvas.drawLine(0, start, BOOK_WIDTH, start, GRID_PAINT);
						start += BOOK_BBLOCK_HEIGHT;
					}
					start = BOOK_BBLOCK_WIDTH;
					while (start < BOOK_WIDTH) {
						canvas.drawLine(start, 0, start, BOOK_HEIGHT, GRID_PAINT);
						start += BOOK_BBLOCK_HEIGHT;
					}
				}
				return _bmpBblock;
			}
			default : {
				Log.e("BOOKMASTER", "Unknown booktype");
				if(_bmpBlank == null)
					_bmpBlank = Bitmap.createBitmap(BOOK_WIDTH, BOOK_HEIGHT, Bitmap.Config.ARGB_8888);
				return _bmpBlank;
			}
		}
	}

	// private

	static private BookMaster	_instance = null;

	private Bitmap				_bmpCover = null;
	private Bitmap				_bmpLine = null;
	private Bitmap				_bmpSblock = null;
	private Bitmap				_bmpBblock = null;
	private Bitmap				_bmpBlank = null;

	private BookMaster() {}

	private Bitmap getCover() {
		if(_bmpCover == null)
			_bmpCover = BitmapFactory.decodeResource(Main.instance().getResources(), R.drawable.cover_line);
		return _bmpCover;
	}

	private long			jniHandler;

	private native long		jniOpen(String filename);
	private native String	jniGetFormat();
	private native int		jniCountPages();
	private native void		jniGoTo(int page);
	private native float	jniGetWidth();
	private native float	jniGetHeight();
	private native boolean	jniDraw(Bitmap bmp, int w, int h, int x, int y, int pw, int ph);

	static {
		System.loadLibrary("mypdf");
	}

	private synchronized int countPages() {
		return jniCountPages();
	}

	private synchronized void draw(Bitmap bmp, int w, int h, int x, int y, int pw, int ph) {
		jniDraw(bmp, w, h, x, y, pw, ph);
	}

	private Bitmap getPDFBitmap(String title, String subTitle, int page) {
		String pdf = title;
		pdf += subTitle;
		pdf = pdf.replaceAll(" ", "");
		pdf = pdf.toLowerCase();
		pdf = Environment.getExternalStorageDirectory().getAbsolutePath() + "/student/" + pdf;
		pdf += "/p" + page + ".pdf";
		Log.i("PDF", "Get " + pdf);
		File pdfFile = new File(pdf);
		if(!pdfFile.exists())
			return null;
		try {
			jniHandler = jniOpen(pdf);
			if (jniHandler == 0) {
				throw new Exception(String.format(Main.instance().getString(R.string.cannot_open_file_Path), pdf));
			}
			String fileFormat = jniGetFormat();
			int pages = countPages();
			Log.i("PDF", "File format:" + fileFormat + " pages:" + pages);
			jniGoTo(0);
			int w = (int)jniGetWidth();
			int h = (int)jniGetHeight();
			Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
			if(!jniDraw(bmp, w, h, 0, 0, w, h))
				throw new Exception("jniDraw failed");
			return bmp;
		}
		catch(Exception e) {
			Log.e("PDF", e.getMessage());
		}
		return null;
	}

}
